package com.crm.task;

import cn.hutool.core.bean.BeanUtil;
import com.crm.domain.entity.Customer;
import com.crm.domain.entity.CustomerLoss;
import com.crm.mapper.CustomerLossMapper;
import com.crm.mapper.CustomerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 客户流失任务
 *
 * @author wb
 * @since 2024-09-03
 */

@Component
@EnableScheduling
public class CustomerLossTask {

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private CustomerLossMapper customerLossMapper;


    @Scheduled(cron = "0 0 1 * * ?")  // 每天凌晨一点执行
    public void lossTask() {
        List<Customer> lossCustomer = customerMapper.findLossCustomer();

        lossCustomer.forEach(customer -> {
            CustomerLoss customerLoss = toCustomerLoss(customer);

            // 保存即将流失的客户
            customerLossMapper.insert(customerLoss);

            // 移除客户
            customerMapper.delete(customer.getId());
        });

    }

    /**
     * 将 Customer 转换成 CustomerLoss
     *
     * @param customer 客户
     * @return 流失客户
     */
    private CustomerLoss toCustomerLoss(Customer customer) {
        CustomerLoss customerLoss = new CustomerLoss();

        BeanUtil.copyProperties(customer, customerLoss, "id", "isValid", "createDate", "isDeleted");
        customerLoss.setState(0);

        return customerLoss;
    }
}
